﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Xml;

namespace Codemonk.Excel.Parser
{
    internal static class Configuration
    {
        const string ConfigFilePath = "./codemonk.excel.parser.xml";
        private static Dictionary<string, Regex> regexs = new Dictionary<string, Regex>();
        static Configuration()
        {
            new Action(() =>
            {
                var document = new XmlDocument();
                document.Load(string.Concat(System.IO.Path.GetDirectoryName(typeof(Configuration).Assembly.CodeBase), ConfigFilePath));
                
                #region 构造Action
                Action<XmlDocument, string, Action<XmlNode>> action = (doc, xpath, nodeAction) =>
                {
                    new Action(() =>
                    {
                        var selectedNodes = document.SelectNodes(xpath);
                        if (selectedNodes == null) return;
                        foreach (XmlNode selectedNode in selectedNodes)
                        {
                            try
                            {
                                nodeAction(selectedNode);
                            }
                            catch { }
                        }
                    }).SafeInvoke();
                };
                Action<string, Action<XmlNode>> reader = (xpath, nodeAction) => action(document, xpath, nodeAction);
                #endregion
                
                //读取正则
                new Action(() =>
                {
                    reader("/codemonk.excel.parser/regexs/regex", node =>
                    {
                        var name = node.As<string>("@name", ConverterExtensions.AsString, null);
                        var pattern = node.As<string>("@pattern", ConverterExtensions.AsString, null);
                        regexs[name] = new Regex(pattern, RegexOptions.Compiled);
                    });
                }).SafeInvoke();



            }).SafeInvoke();
        }

        private static O GetValue<O, I>(I input, IDictionary<I, O> source, O defaultValue = default(O))
        {
            try
            {
                O output;
                if (source.TryGetValue(input, out output)) return output;
                return defaultValue;
            }
            catch
            {
                return defaultValue;
            }
        }

        internal static Regex GetRegex(string name)
        {
            return GetValue(name, regexs, null);
        }
    }
}
